package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.entity.QiShou;
import com.example.backend.mapper.IQiShouMapper;
import com.example.backend.service.IQiShouService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class QiShouService implements IQiShouService {
    @Resource
    private IQiShouMapper qiShouMapper;

    @Override
    public boolean addQiShou(QiShou qiShou) {
        return qiShouMapper.insert(qiShou) > 0 ;
    }

    @Override
    public boolean deleteQiShou(Integer qsid) {
        return qiShouMapper.deleteById(qsid) > 0;
    }

    @Override
    public boolean updateQiShou(QiShou qiShou) {
        return qiShouMapper.updateById(qiShou) > 0;
    }

    @Override
    public IPage<QiShou> selectQiShouByCondition(QiShou qiShou, Integer currentPage, Integer pageSize, String sortField, String sortOrder) {
        LambdaQueryWrapper<QiShou> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(qiShou.getQsid() != null, QiShou::getQsid, qiShou.getQsid())
                .eq(qiShou.getYhid() != null, QiShou::getYhid, qiShou.getYhid())
                .like(StringUtils.hasText(qiShou.getQsmz()), QiShou::getQsmz, qiShou.getQsmz());
        // 应用排序逻辑
        if (sortField != null && !sortField.isEmpty() && sortOrder != null && !sortOrder.isEmpty()) {
            SFunction<QiShou, ?> column = getColumnByField(sortField);
            if (column != null) {
                if ("asc".equalsIgnoreCase(sortOrder)) {
                    wrapper.orderByAsc(column);
                } else {
                    wrapper.orderByDesc(column);
                }
            }
        }

        // 创建 Page 对象，传入当前页码和每页显示数量
        Page<QiShou> page = new Page<>(currentPage, pageSize);
        // 调用分页查询方法
        return qiShouMapper.selectPage(page, wrapper);
    }

    @Override
    public QiShou selectQiShouByYhid(Integer yhid) {
        LambdaQueryWrapper<QiShou> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QiShou::getYhid, yhid);
        return qiShouMapper.selectOne(wrapper);
    }

    private SFunction<QiShou, ?> getColumnByField(String field) {
        return switch (field) {
            case "qsid" -> QiShou::getQsid;
            case "yhid" -> QiShou::getYhid;
            case "qsmz" -> QiShou::getQsmz;
            default -> null;
        };
    }
}
